﻿using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Util.Common;

namespace Util.Redis
{
    public class Redis
    {
        static RedisClient redisClient = new RedisClient(WebAppSettingConfig.RedisHostAddress, WebAppSettingConfig.RedisPort);//redis服务IP和端口

        /// <summary>
        /// 获取Redis Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            try
            {
                return redisClient.Get<T>(key);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取Redis String
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetRedisValue(string key)
        {
            try
            {
                return redisClient.Get<string>(key);
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        /// <summary>
        /// Redis 存储
        /// </summary>
        /// <param name="key"></param>
        /// <param name="velue"></param>
        /// <returns></returns>
        public static void Set(string key, object value)
        {
            try
            {
                redisClient.Set(key, value);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 订阅消息
        /// </summary>
        /// <param name="messaeName">消息名称</param>
        /// <returns></returns>
        public static string Subscription(string messaeName)
        {
            string message = string.Empty;
            using (redisClient)
            {
                IRedisSubscription subscription = redisClient.CreateSubscription();
                subscription.SubscribeToChannels(messaeName);
                subscription.OnMessage = (channel, msg) =>
                {
                    message = msg;
                };
            }
            return message;
        }
        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="messageName">消息名称</param>
        /// <param name="message">消息内容</param>
        public static void PublishMessage(string messageName, string message)
        {

            using (redisClient)
            {
                redisClient.PublishMessage(messageName, message);
            }
        }



    }
}
